package com.geezdata.cps.base.filter;


import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.filter.OncePerRequestFilter;



public class CorsFilter extends OncePerRequestFilter {
	private String accessControlAllowOrigin;
    public String getAccessControlAllowOrigin() {
		return accessControlAllowOrigin;
	}
	public void setAccessControlAllowOrigin(String accessControlAllowOrigin) {
		this.accessControlAllowOrigin = accessControlAllowOrigin;
	}

	@Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, 
    		FilterChain filterChain) throws ServletException, IOException {
        response.setHeader("Access-Control-Allow-Origin", this.accessControlAllowOrigin);
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", 
        		"Origin, X-Requested-With, Content-Type, Accept, X-HTTP-Method-Override, Cookie, AccessToken, AppId");
        response.setHeader("Access-Control-Max-Age", "1728000");
        response.addHeader("Access-Control-Expose-Headers", "AccessToken");
        if ("OPTIONS".equals(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_NO_CONTENT);
        } else { 
            filterChain.doFilter(request, response);
        }
    }
}
